<template>
  <div class="goods-form app-container">
    <div class="form-main">
      <el-steps class="mb-4" :space="200" :active="active" simple>
        <el-step title="基本信息" icon="Document" />
        <el-step title="商品规格" icon="Operation" />
        <!--        <el-step title="商品图片" icon="Picture"/>-->
        <el-step title="商品详情" icon="Reading" />
      </el-steps>
      <div class="form-content">
        <el-form ref="ruleFormRef" :model="form" :rules="rules" :label-width="'110px'">
          <div v-show="active === 1" class="step">
            <el-form-item label="商品名称：" prop="name" :required="true">
              <el-input
                v-model="form.name"
                size="large"
                placeholder="请输入商品名称"
                style="width: 300px"
              />
            </el-form-item>
            <el-form-item label="商品子标题：">
              <el-input
                v-model="form.extra_attributes2.sub_title"
                size="large"
                placeholder="请输入商品子标题"
                style="width: 300px"
              />
            </el-form-item>
            <el-form-item label="商品产地：">
              <el-input
                v-model="form.extra_attributes2.origin"
                size="large"
                placeholder="请输入商品产地"
                style="width: 300px"
              />
            </el-form-item>
            <el-form-item label="商品标签：">
              <div>
                <el-input
                  v-model="label_name"
                  size="large"
                  style="width: 300px"
                  placeholder="输入后按回车添加"
                  @keyup.enter="addLabelValue"
                />
                <div style="margin-top: 10px">
                  <el-tag
                    v-for="(value, index) in form.extra_attributes2.label"
                    :key="index"
                    size="large"
                    closable
                    @close="removeSpecValue(index)"
                  >
                    {{ value }}
                  </el-tag>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="商品单位：" prop="uom_id" :required="true">
              <el-select
                v-model="form.uom_id"
                size="large"
                placeholder="请选择商品单位"
                style="width: 300px"
              >
                <el-option v-for="uom in uomList" :key="uom.id" :label="uom.name" :value="uom.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="商品类别：" prop="category_id" :required="true">
              <el-select
                v-model="form.category_id"
                size="large"
                placeholder="请选择商品类别"
                style="width: 300px"
                @change="categoryChange"
              >
                <el-option
                  v-for="category in categoryList"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="商品品牌：">
              <el-select
                v-model="form.brand_id"
                size="large"
                placeholder="请选择商品品牌"
                style="width: 300px"
              >
                <el-option
                  v-for="brand in brandList"
                  :key="brand.id"
                  :label="brand.name"
                  :value="brand.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="运费模板" prop="exps_temp_id">
              <el-select
                v-model="form.exps_temp_id"
                size="large"
                placeholder="请选择运费模板"
                style="width: 300px"
              >
                <el-option
                  v-for="item in shippingTemplateStore.list"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="最小销售数量：">
              <el-input
                v-model="form.min_sale_quantity"
                size="large"
                placeholder="请输入最小输入数量"
                style="width: 300px"
              />
            </el-form-item>
            <el-form-item label="库存不足下单：">
              <el-radio-group v-model="form.is_order_out_stock">
                <el-radio :value="true" size="large">允许</el-radio>
                <el-radio :value="false" size="large">不允许</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="是否热销：">
              <el-radio-group v-model="form.is_hot">
                <el-radio :value="true" size="large">是</el-radio>
                <el-radio :value="false" size="large">否</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="收银必备：">
              <el-radio-group v-model="form.is_pos">
                <el-radio :value="true" size="large">是</el-radio>
                <el-radio :value="false" size="large">否</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="新品推荐：">
              <el-radio-group v-model="form.is_new_recommend">
                <el-radio :value="true" size="large">是</el-radio>
                <el-radio :value="false" size="large">否</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="每周推荐：">
              <el-radio-group v-model="form.is_week_recommend">
                <el-radio :value="true" size="large">是</el-radio>
                <el-radio :value="false" size="large">否</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="封面图片：" prop="sub_images" :required="true">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                name="file"
                :headers="{ Authorization: accessToken }"
                :before-upload="onBeforeUpload"
                :on-success="onUploadSuccess"
                :on-error="onUploadError"
                :show-file-list="false"
              >
                <img v-if="form.image_url" :src="form.image_url" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>

            <el-form-item label="商品多图：" prop="sub_images" :required="true">
              <el-upload
                v-model:file-list="fileList"
                class="upload-demo"
                :action="uploadUrl"
                name="file"
                :headers="{ Authorization: accessToken }"
                multiple
                :on-success="handleSuccess"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-upload="onBeforeUpload"
                :limit="9"
                list-type="picture-card"
                :on-exceed="handleExceed"
              >
                <el-icon>
                  <Plus />
                </el-icon>
                <template #tip>
                  <div class="el-upload__tip">图片必须小于5MB的jpg/png文件</div>
                  (建议尺寸：640 x 640 像素)
                </template>
              </el-upload>
            </el-form-item>
          </div>
          <div v-show="active === 2" class="step">
            <el-form-item label="商品规格：">
              <el-radio-group v-model="suk_type" @change="onSukTypeChange">
                <el-radio :value="1" size="large">单规格</el-radio>
                <el-radio :value="2" size="large">多规格</el-radio>
              </el-radio-group>
            </el-form-item>
            <div v-if="suk_type === 1 && form.skus.length > 0">
              <!--              <el-form-item label="图片：" prop="image_url" :required="true">-->
              <!--                <el-upload-->
              <!--                  class="avatar-uploader2"-->
              <!--                  :action="uploadUrl"-->
              <!--                  name="file"-->
              <!--                  :headers="{'Authorization': accessToken}"-->
              <!--                  :before-upload="onBeforeUpload"-->
              <!--                  :on-success="(response, file, fileList) => onUploadSuccess2(response, file, fileList, 0)"-->
              <!--                  :on-error="onUploadError"-->
              <!--                  :show-file-list="false">-->
              <!--                  <img v-if="form.skus[0].image_url" :src="form.skus[0].image_url" class="avatar"/>-->
              <!--                  <el-icon v-else class="avatar-uploader-icon">-->
              <!--                    <Plus/>-->
              <!--                  </el-icon>-->
              <!--                </el-upload>-->
              <!--              </el-form-item>-->
              <el-form-item label="销售价格：" :required="true">
                <el-input
                  v-model="form.skus[0].sale_price"
                  size="large"
                  placeholder="请输入销售价格"
                  style="width: 300px"
                />
              </el-form-item>
              <el-form-item label="标准价格：" :required="true">
                <el-input
                  v-model="form.skus[0].stand_price"
                  size="large"
                  placeholder="请输入标准价格"
                  style="width: 300px"
                />
              </el-form-item>
              <el-form-item label="指导价格：" :required="true">
                <el-input
                  v-model="form.skus[0].guiding_price"
                  size="large"
                  placeholder="请输入指导价格"
                  style="width: 300px"
                />
              </el-form-item>
              <el-form-item label="体积" prop="volume">
                <el-input
                  v-model="form.skus[0].volume"
                  size="large"
                  placeholder="请输入体积"
                  style="width: 300px"
                >
                  <template #suffix>m²</template>
                </el-input>
              </el-form-item>
              <el-form-item label="重量" prop="weight">
                <el-input
                  v-model="form.skus[0].weight"
                  size="large"
                  placeholder="请输入重量"
                  style="width: 300px"
                >
                  <template #suffix>KG</template>
                </el-input>
              </el-form-item>
              <el-form-item label="商品库存：" :required="true">
                <el-input
                  v-model="form.skus[0].stock"
                  size="large"
                  placeholder="请输入商品库存"
                  style="width: 300px"
                />
              </el-form-item>
              <el-form-item label="条形码：">
                <el-input
                  v-model="form.skus[0].barcode"
                  size="large"
                  placeholder="请输入商品条形码"
                  style="width: 300px"
                />
              </el-form-item>
            </div>
            <div v-else-if="suk_type === 2">
              <el-form-item label="商品规格：">
                <multiSpecs
                  :uploadUrl="uploadUrl"
                  :accessToken="accessToken"
                  :attributesData="form.extra_attributes"
                  :skuData="form.skus"
                  :isEdit="goods_id > 0"
                  @skusChange="skusChange"
                />
              </el-form-item>
            </div>
          </div>
          <div v-show="active === 3" class="step">
            <el-form-item
              v-if="form.detail_images && form.detail_images.length > 0"
              label="商品多图："
            >
              <div class="detail-images">
                <p v-for="(img, inx) in form.detail_images" :key="inx" style="margin: 0">
                  <img v-if="img" width="100%" :src="img" alt="" />
                </p>
              </div>
            </el-form-item>
            <el-form-item v-else label="商品详情：">
              <WangEditor v-model="form.description" />
            </el-form-item>
          </div>
          <div class="button-box">
            <el-button v-if="active == 1" size="large" @click="router.go(-1)">返回</el-button>
            <el-button v-if="active > 1" size="large" @click="onStepChange('up')">上一步</el-button>
            <el-button v-if="active < 3" size="large" type="success" @click="onStepChange('down')">
              下一步
            </el-button>
            <el-button
              v-if="active === 3"
              size="large"
              type="success"
              @click="onSaveSubmit(ruleFormRef)"
            >
              确定提交
            </el-button>
          </div>
        </el-form>
      </div>
    </div>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import multiSpecs from "./components/multiSpecs.vue";
import router from "@/router";
import { useRoute } from "vue-router";
import GoodsAPI, { GoodsQueryForm } from "@/api/goods/goods";
import FileAPI from "@/api/file";
import WangEditor from "@/components/WangEditor/index.vue";
import { getToken } from "@/utils/auth";
import { useUserStore } from "@/store";

import type { UploadProps, UploadUserFile, FormInstance, FormRules } from "element-plus";
import { useShippingTemplateStoreHook } from "@/store/modules/goods/shipping-template";

const userStore = useUserStore();
const shippingTemplateStore = useShippingTemplateStoreHook();
const dialogVisible = ref(false);
const dialogImageUrl = ref("");
const accessToken = ref(getToken());
const uploadUrl = ref(FileAPI.uploadUrl);
const active = ref(1);
const suk_type = ref(1); //1单规格 2多规格
const uom_name = ref("");
const label_name = ref("");
const fileList = ref<UploadUserFile[]>([]);
const ruleFormRef = ref<FormInstance>();
const form = ref({
  sale_number: "", //销售数量
  supplier: userStore.supplierInfo?.id || "",
  uom_id: "",
  brand_id: "",
  category_id: "",
  name: "",
  image_url: "",
  sub_images: [],
  detail_images: [],
  description: "",
  is_order_out_stock: true,
  express_amount: 0,
  min_sale_quantity: 1,
  is_hot: false,
  is_pos: false,
  is_week_recommend: false,
  is_new_recommend: false,
  origin: userStore.isSupplier ? "supplier" : "",
  extra_attributes: [],
  volume: "",
  weight: "",
  extra_attributes2: {
    sub_title: "",
    label: [],
    service: [],
    origin: "",
  },
  exps_temp_id: undefined,
  skus: [
    {
      barcode: "",
      stand_price: "",
      sale_price: "",
      stock: "",
      guiding_price: "",
      is_active: true,
      image_url: "",
      attributes: [],
      weight: "",
      volume: "",
    },
  ],
});
const goods_id = ref(0);

const rules = reactive<FormRules<GoodsQueryForm>>({
  name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  uom_id: [{ required: true, message: "请选择商品单位", trigger: "blur" }],
  category_id: [{ required: true, message: "请选择商品类别", trigger: "blur" }],
  image_url: [{ required: true, message: "请上传商品封面图", trigger: "blur" }],
  sub_images: [{ required: true, message: "请上传商品多图", trigger: "blur" }],
});

const onBeforeUpload: UploadProps["beforeUpload"] = (file) => {
  if (file.type != "image/jpeg" && file.type != "image/png") {
    ElMessage.error("图片类型仅支持PNG,JPG！");
    return false;
  } else if (file.size / 1024 / 1024 > 5) {
    ElMessage.error("图片大小不能超过5MB！");
    return false;
  }
  return true;
};

function addLabelValue() {
  const value = label_name.value.trim();
  if (!value) {
    ElMessage.info("标签内容不能为空");
  } else if (value && !form.value.extra_attributes2.label.includes(value)) {
    form.value.extra_attributes2.label.push(value);
    label_name.value = "";
  } else {
    ElMessage.info("该标签已存在");
  }
}

function removeSpecValue(index) {
  form.value.extra_attributes2.label.splice(index, 1);
}

const onUploadSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  ElMessage.success("上传成功");
  form.value.image_url = response.url;
};

const onUploadSuccess2: UploadProps["onSuccess"] = (response, file, fileList, index) => {
  ElMessage.success("上传成功");
  form.value.skus[index].image_url = response.url;
};

const onUploadError: UploadProps["onError"] = (file) => {
  ElMessage.error("上传失败");
  console.log("error==", file);
};

const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(fileList.value);
  fileList.value.forEach((item, index) => {
    if (item.uid === file.uid) {
      fileList.value.splice(index, 1);
    }
  });
};

const handleSuccess: UploadProps["onSuccess"] = (file, uploadFiles) => {};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.response.url;
  dialogVisible.value = true;
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(
    `限制图片为9张, 您选择了 ${files.length} 张图片, 总共 ${
      files.length + uploadFiles.length
    } 张图片`
  );
};

const onStepChange = (type) => {
  if (type == "up") {
    active.value--;
  } else if (type == "down") {
    active.value++;
  }
};

function onSukTypeChange(val) {
  if (val === 1) {
    form.value.skus = [
      {
        barcode: "",
        stand_price: "",
        sale_price: "",
        stock: "",
        guiding_price: "",
        image_url: "",
        is_active: true,
        attributes: [],
        volume: "",
        weight: "",
        exps_temp_id: undefined,
      },
    ];
  } else if (val === 2) {
    form.value.skus = [];
  }
}

function skusChange(data) {
  console.log(data);
  form.value.skus = data.skus;
  form.value.extra_attributes = data.specs;
}

const onSaveSubmit = async (formEl: FormInstance | undefined) => {
  form.value.sub_images = [];
  fileList.value.forEach((item) => {
    if (item.response?.url) {
      form.value.sub_images.push(item.response?.url);
    } else if (item.url) {
      form.value.sub_images.push(item.url);
    }
  });
  console.log(form.value);
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (suk_type.value === 1) {
        form.value.skus[0].image_url = form.value.image_url;
        form.value.skus[0].attributes = [
          {
            key: "商品规格",
            value: uom_name,
          },
        ];
        form.value.extra_attributes = [
          {
            name: "商品规格",
            data: [uom_name],
          },
        ];
      } else if (suk_type.value === 2) {
        const specs = form.value.extra_attributes.map((item) => {
          delete item.newValue;
          item.data = item.values;
          delete item.values;
          return item;
        });
        form.value.extra_attributes = specs;
      }
      if (goods_id.value > 0) {
        await GoodsAPI.putGoods(form.value, goods_id.value);
        ElMessage.success("新增成功，等待平台审核！");
      } else {
        form.value.skus.forEach((item) => {
          item.barcode = item.barcode || "无";
        });
        await GoodsAPI.postGoods(form.value);
        ElMessage.success("修改成功，等待平台审核！");
      }
      router.go(-1);
    } else {
      console.log("必填内容不能为空！");
    }
  });
};

const categoryList = ref([]);
const getCategoryData = async () => {
  const response = await GoodsAPI.getCategories({ all: 1 });
  categoryList.value = response;
};
const categoryChange = (e) => {
  getBrandData();
};
const brandList = ref([]);
const getBrandData = async () => {
  const response = await GoodsAPI.getBrand();
  brandList.value = response;
};
const uomList = ref([]);
const getProductUom = async () => {
  const response = await GoodsAPI.getUom();
  uomList.value = response;
};

const getGoodsDetail = async () => {
  const goods: any = await GoodsAPI.getGoodsDetail(goods_id.value);
  if (goods) {
    form.value.exps_temp_id = goods.exps_temp?.id || "";
    form.value.supplier = goods.supplier?.id || "";
    form.value.uom_id = goods.uom?.id || "";
    form.value.brand_id = goods.brand?.id || "";
    form.value.category_id = goods.category?.id || "";
    form.value.name = goods.name;
    form.value.image_url = goods.image_url;
    form.value.sub_images = goods.image_urls;
    form.value.description = goods.description;
    form.value.express_amount = goods.express_amount || 0;
    form.value.min_sale_quantity = goods.min_sale_quantity;
    form.value.extra_attributes = goods.extra_attributes;
    form.value.origin = goods.origin;
    form.value.skus = goods.skus;
    form.value.detail_images = goods.detail_images;
    form.value.is_hot = goods.is_hot || false;
    form.value.is_pos = goods.is_pos || false;
    form.value.is_week_recommend = goods.is_week_recommend || false;
    form.value.is_new_recommend = goods.is_new_recommend || false;
    form.value.extra_attributes2 = goods.extra_attributes2 || {
      sub_title: "",
      label: [],
      service: [],
      origin: "",
    };
    form.value.is_order_out_stock = goods.is_order_out_stock;
    suk_type.value = goods.extra_attributes.length > 1 ? 2 : 1;
    uom_name.value = goods.uom?.name || "";
    if (form.value.category_id) {
      getBrandData();
    }
    if (goods.image_urls) {
      for (let i = 0; i < goods.image_urls.length; i++) {
        if (goods.image_urls[i]) {
          fileList.value.push({
            uid: i,
            name: i + ".png",
            url: goods.image_urls[i],
          });
        }
      }
    }
  }
};

const route = useRoute();
onMounted(() => {
  if (route.query.id) {
    goods_id.value = route.query.id;
    getGoodsDetail();
  }
  getProductUom();
  getCategoryData();
  shippingTemplateStore.fetchShippingTemplateList({ page: 1, size: 99999 });
});
</script>

<style scoped lang="scss">
.form-main {
  padding: 15px;
  border-radius: 10px;
  background-color: #ffffff;

  .form-content {
    padding: 30px;

    .upload-demo .avatar,
    .avatar-uploader .avatar {
      width: 100px;
      height: 100px;
      display: block;
    }

    .avatar-uploader2 .avatar {
      width: 80px;
      height: 80px;
      display: block;
    }

    .button-box {
      text-align: right;
    }
  }
}
</style>

<style>
.upload-demo .el-upload,
.avatar-uploader .el-upload,
.avatar-uploader2 .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.upload-demo .el-upload:hover,
.avatar-uploader .el-upload:hover,
.avatar-uploader2 .el-upload:hover {
  border-color: var(--el-color-primary);
}

.upload-demo .el-icon.avatar-uploader-icon,
.avatar-uploader .el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}

.avatar-uploader2 .el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
}
</style>
